package realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.text.PropertiesRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class MyRealm extends AuthorizingRealm {
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("AuthenticationInfo.doGetAuthenticationInfo");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        Properties p = new Properties();

        try {
            if (path.startsWith("classpath:")) {
                path = path.substring(10);
                p.load(PropertiesRealm.class.getClassLoader().getResourceAsStream(path));
            } else if (path.startsWith("file:")) {
                path.substring(5);
                p.load(new FileInputStream(path));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String password = p.getProperty("user." + username);
        if (password == null) {
            throw new UnknownAccountException("你的账号或者密码错误：username=" + username);
        }

        return new SimpleAuthenticationInfo(username+"@qq.com", password, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("MyRealm.doGetAuthorizationInfo");

        return null;
    }

}
